package com.cnhis.cloudhealth.clinical.hosnurse.hosstopadvice.bo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import com.cnhis.cloudhealth.commons.utils.*;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import com.cnhis.cloudhealth.clinical.hosnurse.hosstopadvice.dao.HosStopAdviceDao;
import com.cnhis.cloudhealth.commons.Mappers.ModelVo;
import com.cnhis.cloudhealth.commons.newid.GetNewId;

import net.sf.json.JSONObject;

@SuppressWarnings({ "rawtypes", "unchecked" })
@Service
public class HosStopAdviceBo {
	@Resource
	private HosStopAdviceDao hosStopAdviceDao;
	@Resource
	private GetNewId getNewId;

	private ModelVo packModelVo(String nid,Map map){
		ModelVo mo = new ModelVo();
		List<Map<String,String>> list = null;
		try {
			list = hosStopAdviceDao.queryForList(nid,map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(list!=null&&list.size()>0) {

			mo.setList(list);
			mo.setResult(StaticKeys.OH_SUCCESS);
			mo.setTotal(list.size());
		}
		return mo;
	}

	public ModelVo nurseVerifyStopAdvice(Map map, int currPage, int pageSize) throws Exception {
		ModelVo mo = new ModelVo();
		map.put("lDate", DateUtils.getDateString(new Date()));
		Integer adstopint = hosStopAdviceDao.adstopviceint(map);
		Page pg = hosStopAdviceDao.nurseVerifyStopAdvice(map, currPage, pageSize);
		List<Map<String, Object>> list = pg.getList();

		mo.setList(list);
		mo.setRows(list);
		mo.setTotal(pg.getTotalNumber());
		mo.setUserdata("{totalsize:"+pg.getTotalNumber()+"}");
		mo.setResult(StaticKeys.OH_SUCCESS);
		mo.setPage(currPage);
		mo.setRecords(adstopint);
		mo.setTotalPage(pg.getTotalPage());
		return mo;
	}

	public ModelVo checkStopAdvice(Map map) throws Exception {
		ModelVo mo = new ModelVo();
		List list = hosStopAdviceDao.checkStopAdvice(map);
		mo.setList(list);
		mo.setRows(list);
		mo.setResult(StaticKeys.OH_SUCCESS);

		return mo;

	}

	private boolean VAFState(Map map) throws Exception {
		return hosStopAdviceDao.VAFState(map) > 0;
	}

	private void nurseOrderStopValidate(Map map) throws Exception {
		Long vbg01 = getNewId.nextId();
		map.put("vbg01",vbg01);
		hosStopAdviceDao.nurseOrderStopValidate(map);
	}

	public ModelVo execNurseOrderStopValidate(Map map) throws Exception {
		ModelVo mo = new ModelVo(StaticKeys.OH_SUCCESS);
		String json = map.get("lXML").toString();
		JSONObject object = JSONObject.fromObject(json);
		
		List<Map<String,Object>> list = JsonUtil.getList(object.getJSONArray("VAF1").toString());
		for (Map<String,Object> m : list) {
			m.put("uid", getNewId.nextId());
		}
		map.put("ls", list);
		if (VAFState(map)) {
			mo.setResultMsg("已有医嘱记录状态发生变化，请返回重新选择过滤条件");
			mo.setResult(StaticKeys.OH_FALSE);
			return mo;
		}
		nurseOrderStopValidate(map);
		return mo;
	}

	private Long getVAF01A(Map map) throws Exception {
		return hosStopAdviceDao.getVAF01A(map);
	}

	public ModelVo execNurseOrderStopDoubt(Map map) throws Exception {
		ModelVo mo = new ModelVo(StaticKeys.OH_SUCCESS);
		String lBDA01 = MapUtils.getString(map,"lBDA01","");
		Long lVAF01 = MapUtils.getLong(map,"lVAF01",0l);
		Long vaf01a = lVAF01;
		if(lBDA01.charAt(0) >= '1' && lBDA01.charAt(0) <= '2'){
			vaf01a = getVAF01A(map);
		}
		map.put("VAF01A", vaf01a==null?0:vaf01a);
		map.put("lDate", DateUtils.getDateString(new Date()));
		map.put("VBG01", getNewId.nextId());
		// 新增医嘱状态记录
		hosStopAdviceDao.insertVBG2(map);
		return mo;
	}
	//
	private String transferLongToDate(String dateFormat, String millSec) {
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		boolean bool = true;
		Date date = new Date();			
		try {
			date = sdf.parse(millSec);
		} catch (ParseException e) {
			bool = false;
		}
		if(!bool){
			Long mill = Long.parseLong(millSec);																// HH:mm:s			
			date = new Date(mill);
		}
		return sdf.format(date);
	}
	//
	public boolean isDateStr(String str) {
		boolean bool = true;
		try {			
			new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(str);
		} catch (Exception e) {
			bool = false;
		}
		return bool;
	}

	private List formatLongDate(List<Map<String, Object>> VAF2) throws Exception {
		for (Map<String, Object> m : VAF2) {
			if (m.containsKey("vaf36")) {
				if (null != m.get("vaf36")) {
					String vaf36 = m.get("vaf36").toString();
					if (!isDateStr(vaf36)) {
						String date = transferLongToDate("yyyy-MM-dd HH:mm:ss", vaf36);
						m.put("vaf36", date);
					}
				}
			}
			if (m.containsKey("vaf37")) {
				if (null != m.get("vaf37")) {
					String vaf37 = m.get("vaf37").toString();
					if (!isDateStr(vaf37)) {
						String date = transferLongToDate("yyyy-MM-dd HH:mm:ss", vaf37);
						m.put("vaf37", date);
					}
				}
			}
			if (m.containsKey("vaf38")) {
				if (null != m.get("vaf38")) {
					String vaf38 = m.get("vaf38").toString();
					if (!isDateStr(vaf38)) {
						String date = transferLongToDate("yyyy-MM-dd HH:mm:ss", vaf38);
						m.put("vaf38", date);
					}
				}
			}
			if (m.containsKey("avaf38")) {
				if (null != m.get("avaf38")) {
					String aVAF38 = m.get("avaf38").toString();
					if (!isDateStr(aVAF38)) {
						String date = transferLongToDate("yyyy-MM-dd HH:mm:ss", aVAF38);
						m.put("avaf38", date);

					}
				}
			}

			if (m.containsKey("vaf47")) {
				if (null != m.get("vaf47")) {
					String vaf47 = m.get("vaf47").toString();
					if (!isDateStr(vaf47)) {
						String date = transferLongToDate("yyyy-MM-dd HH:mm:ss", vaf47);
						m.put("vaf47", date);

					}
				}
			}
			if (m.containsKey("vaf50")) {
				if (null != m.get("vaf50")) {
					String vaf50 = m.get("vaf50").toString();
					if (!isDateStr(vaf50)) {
						String date = transferLongToDate("yyyy-MM-dd HH:mm:ss", vaf50);
						m.put("vaf50", date);

					}
				}
			}
		}
		return VAF2;
	}

	public ModelVo execNurseAdviceAutoStop(Map map) throws Exception {
		ModelVo mo = new ModelVo(StaticKeys.OH_SUCCESS);
		String lxml = map.get("lXml").toString();
		JSONObject jsonVAF2 = JSONObject.fromObject(lxml);
		// 医嘱
		List<Map<String, Object>> VAF2 = JsonUtil.getList(jsonVAF2.getJSONArray("VAF1").toString());
		// 参数
		
		List<Map<String, Object>> TPara = JsonUtil.getList(jsonVAF2.getJSONArray("TPara").toString());		
		// 医嘱
		// 格式化时间
		VAF2 = formatLongDate(VAF2);
		

		map.put("TmpVAFsp", VAF2);
		map.put("TmpPara", TPara);
		map.put("lVBGid", getNewId.nextId());
		if (TPara.size() == 0) {
			return mo;
		}

		List<Map<String, Object>> TmpVAFsp = hosStopAdviceDao.getVAF2(map);
		if (TmpVAFsp.size() == 0) {
			return mo;
		}
		map.put("eDate", DateUtils.getDateString(new Date()));
		map.put("lDate", DateUtils.getDateString(new Date()));
		map.putAll(sysParamValue());

		if (!checkCurrentMethod(TmpVAFsp)) {
			return mo;
		}
		// 3 4 11 5
		if(TmpVAFsp.size()>0){
			for(int i=0;i<TmpVAFsp.size();i++){
				List<Map<String, Object>> TmpVAFspi = new ArrayList<>();
				List<Map<String, Object>> stopAdvice = new ArrayList<>();
				TmpVAFspi.add(TmpVAFsp.get(i));
				map.put("TmpVAFsp", TmpVAFspi);
				if (checkMethod(TmpVAFsp.get(i))) {
					if (checkMethod2(TmpVAFsp.get(i))) {
						Map m = hosStopAdviceDao.getParams1(map);
						if(m!=null) {
							map.putAll(m);
						}
					} else {
						Map m = hosStopAdviceDao.getParams2(map);
						if(m!=null) {
							map.putAll(m);
						}

					}
					stopAdvice.addAll(getStopVAF21(map));
				} else {
					if (checkMethod22(TmpVAFsp.get(i))) {
						Map m = hosStopAdviceDao.getParams3(map);
						if(m!=null) {
							map.putAll(m);
							stopAdvice.addAll(getStopVAF22(map));
						}
					}
				}
				if (stopAdvice.size() > 0) {
					for (Map<String, Object> mm : stopAdvice) {
						mm.put("vbg01", getNewId.nextId());
					}
					map.put("tmpStop", stopAdvice);
					updateVAF2(map);
				} 
			}
		}		
		return mo;
	}
//全部发送时判断是否停嘱
	public ModelVo execNurseAdviceAutoStopall(Map map) throws Exception {
		ModelVo mo = new ModelVo(StaticKeys.OH_SUCCESS);
		// 医嘱
		List<Map<String, Object>> VAF2 = (List<Map<String, Object>>) map.get("vaf");
		// 参数
		
		List<Map<String, Object>> TPara = (List<Map<String, Object>>) map.get("TPara");
		// 医嘱
		// 格式化时间
		VAF2 = formatLongDate(VAF2);
		

		map.put("TmpVAFsp", VAF2);
		map.put("TmpPara", TPara);
		map.put("lVBGid", getNewId.nextId());
		if (TPara.size() == 0) {
			return mo;
		}

		List<Map<String, Object>> TmpVAFsp = hosStopAdviceDao.getVAF2(map);
		if (TmpVAFsp.size() == 0) {
			return mo;
		}
		map.put("eDate", DateUtils.getDateString(new Date()));
		map.put("lDate", DateUtils.getDateString(new Date()));
		map.putAll(sysParamValue());

		if (!checkCurrentMethod(TmpVAFsp)) {
			return mo;
		}
		// 3 4 11 5
		if(TmpVAFsp.size()>0){
			for(int i=0;i<TmpVAFsp.size();i++){
				List<Map<String, Object>> TmpVAFspi = new ArrayList<>();
				List<Map<String, Object>> stopAdvice = new ArrayList<>();
				TmpVAFspi.add(TmpVAFsp.get(i));
				map.put("TmpVAFsp", TmpVAFspi);
				if (checkMethod(TmpVAFsp.get(i))) {
					if (checkMethod2(TmpVAFsp.get(i))) {
						Map m = hosStopAdviceDao.getParams1(map);
						if(m!=null) {
							map.putAll(m);
						}
					} else {
						Map m = hosStopAdviceDao.getParams2(map);
						if(m!=null) {
							map.putAll(m);
						}

					}
					stopAdvice.addAll(getStopVAF21(map));
				} else {
					if (checkMethod22(TmpVAFsp.get(i))) {
						Map m = hosStopAdviceDao.getParams3(map);
						if(m!=null) {
							map.putAll(m);
							stopAdvice.addAll(getStopVAF22(map));
						}
					}
				}
				if (stopAdvice.size() > 0) {
					for (Map<String, Object> mm : stopAdvice) {
						mm.put("vbg01", getNewId.nextId());
					}
					map.put("tmpStop", stopAdvice);
					updateVAF2(map);
				} 
			}
		}		
		return mo;
	}
	private Map sysParamValue() throws Exception {
		return hosStopAdviceDao.sysParamValue();
	}

	private boolean checkCurrentMethod(List<Map<String, Object>> ls) throws Exception {
		for (Map<String, Object> map : ls) {
			String bda01 = MapUtils.getString(map,"bda01","");
			String bbx13 = MapUtils.getString(map,"bbx13","");
			if ("Z".equals(bda01)){
				if(StringUtils.isNotBlank(bbx13)){
					if ("3".equals(bbx13) || "4".equals(bbx13)
							|| "11".equals(bbx13) || "5".equals(bbx13)
							|| "6".equals(bbx13)) {
						return true;
					}
			   }
			}
		}
		return false;
	}

	private boolean checkMethod(Map<String, Object> map) throws Exception {
		if(map.get("bbx13")!=null){
			if ("3".equals(MapUtils.getString(map,"bbx13","")) || "4".equals(MapUtils.getString(map,"bbx13",""))
					|| "11".equals(MapUtils.getString(map,"bbx13","")) || "5".equals(MapUtils.getString(map,"bbx13",""))) {
				return true;
			}
		}
		return false;
	}

	private boolean checkMethod2(Map<String, Object> map) throws Exception {
		if ("2".equals(map.get("vaf11").toString())) {
			if(map.get("bbx13")!=null){
				if ("3".equals(MapUtils.getString(map,"bbx13","")) || "4".equals(MapUtils.getString(map,"bbx13",""))
						|| "11".equals(MapUtils.getString(map,"bbx13","")) || "5".equals(MapUtils.getString(map,"bbx13",""))) {
					return true;
				}
			}
		}
		return false;
	}

	private boolean checkMethod22(Map<String, Object> map) throws Exception {
		if ("6".equals(MapUtils.getString(map,"bbx13",""))) {
			return true;
		}
		return false;
	}

	private List getStopVAF21(Map map) throws Exception {
		return hosStopAdviceDao.getStopVAF21(map);
	}

	private List getStopVAF22(Map map) throws Exception {
		return hosStopAdviceDao.getStopVAF22(map);
	}

	private void updateVAF2(Map map) throws Exception {
		hosStopAdviceDao.updateVAF2(map);
	}

	private Map getBCQ04B(Map map) throws Exception {
		return hosStopAdviceDao.getBCQ04B(map);
	}

	public ModelVo validateLongAdvice(Map map, int currPage, int pageSize) throws Exception {
		ModelVo mo = new ModelVo();
		map.put("lDate", DateUtils.getDateString(new Date()));
		Map m = getBCQ04B(map);
		if (m != null) {
			if (m.get("vaa04") != null) {
				map.put("VAA04", m.get("vaa04"));

			} else {
				map.put("VAA04", "");
			}
			if (m.get("bcq04b") != null) {
				map.put("BCQ04B", m.get("bcq04b"));
			} else {
				map.put("BCQ04B", "");
			}
		}
		Page pg = hosStopAdviceDao.validateLongAdvice(map, currPage, pageSize);
		List<Map<String, Object>> ls = pg.getList();
		for (Map<String, Object> mm : ls) {
			if (mm.containsKey("vaf01")) {
				mm.put("vaf01", mm.get("vaf01").toString());
			}
		}
		mo.setList(pg.getList());
		mo.setRows(pg.getList());
		mo.setResult(StaticKeys.OH_SUCCESS);
		mo.setTotal(pg.getTotalNumber());
		return mo;
	}

	private String checkOut(Map map) throws Exception {
		if (hosStopAdviceDao.isOut(map) > 0) {
			return hosStopAdviceDao.checkOut(map);
		}
		return "";
	}
	//长嘱停止
	public ModelVo stopOrder(Map<String,Object> map) throws Exception{
		String lXml = MapUtils.getString(map,"lXml","");
		if(StringUtils.isBlank(lXml)){
			return new ModelVo(StaticKeys.OH_FALSE, "参数为空，请检查参数！");
		}
		//将Json数据装换为list
		List<Map<String,Object>> lxmlList = JsonUtil.getList(lXml);
		if(lxmlList==null|| lxmlList.size()==0){
			return new ModelVo(StaticKeys.OH_FALSE, "参数解析有误，请检查！");
		}
		map.put("lxmlList",lxmlList);
		String BCE03 = (String)hosStopAdviceDao.queryToObject("Doctororderstop.stoporder_001",map);
		map.put("lBCE03",BCE03);
		String aSmsg = (String)hosStopAdviceDao.queryToObject("Doctororderstop.stoporder_002",map);
		if(StringUtils.isNotBlank(aSmsg)){
			return new ModelVo(StaticKeys.OH_FALSE, "'"+aSmsg+"'医嘱已经停止，请返回刷新条件重新选择！");
		}
		map.put("lDate",new Date());
		map.put("lTxt","医嘱停止");
		//更新医嘱表
		hosStopAdviceDao.update("Doctororderstop.stoporder_003",map);
		Map<String,Object> ids = (Map<String,Object>)hosStopAdviceDao.queryToObject("Doctororderstop.stoporder_004",map);
		Long lMaxId = MapUtils.getLong(ids,"lmaxid");
		Long lMinId = MapUtils.getLong(ids,"lminid");
		Long lID = getNewId.nextId();
		lID = lID-lMaxId;
		map.put("lMaxId",lMaxId);
		map.put("lMinId",lMinId);
		map.put("lID",lID);
		//插入病人医嘱状态
		hosStopAdviceDao.insert("Doctororderstop.stoporder_005",map);
		//更新病人医嘱提醒
		hosStopAdviceDao.update("Doctororderstop.stoporder_006",map);
		return new ModelVo(StaticKeys.OH_SUCCESS, "停嘱成功！");
	}

	private List getTmpVAFsp(Map map) throws Exception {
		List<Map<String, Object>> ls = hosStopAdviceDao.getTmpVAFsp(map);
		for (Map<String, Object> mm : ls) {
			mm.put("vbg01", getNewId.nextId());
		}
		return ls;
	}

	public ModelVo selectUnstoporder(Map map){
		return packModelVo("HosStopAdvice.1424",map);
	}

	public ModelVo selectUnsendorder(Map map){
		return packModelVo("HosStopAdvice.4182",map);
	}

}
